import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    redirect: '/lunbo',
    children: [
      { path: '/lunbo',component: ()=> import('@/components/lunbo.vue')},
      { path: '/fankui',component: () => import('@/components/fankui.vue')},
      { path: '/geren',component: () => import('@/components/geren.vue')},
      { path: '/tingche',component: () => import('@/components/tingche.vue')},
      { path: '/recharge',component: () => import('@/components/recharge.vue')},
    ]
  },
  {
    path: '/login',
    component: () => import('../views/login.vue')
  },
  {
    path: '/register',
    component: () => import('../views/register.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
router.beforeEach((to, from, next) => {
  const nextRoute = ['/register', '/login'] // 需要登录的页面
  console.log(to.name,from)
  if(nextRoute.indexOf(to.path)>=0){
    console.log("这边")
    next()
  }else {
    console.log("跑这边")
    if(window.localStorage.getItem("token")){
      next()
    }else {
      next('login')
    }
  }
  // let isLogin = window.localStorage.getItem("token")  // 判断是否登录，本地存储有用户数据则视为已经登录
  // // 未登录状态；当路由到 nextRoute 指定页时，跳转至 UserLogIn
  // if (nextRoute.indexOf(to.name) != 0) { // 检测是否登录的页面
  //   if (!isLogin) { // 如果未登录（本地存储无用户数据），并且要跳到登录页面
  //     if (from.name === 'UserLogIn') {
  //       next('/')
  //       return
  //     }
  //   }
  // }
  // 已登录状态；当路由到 UserLogIn 时，跳转至 Home
  // if (to.name === 'UserLogIn') {
  //   if (isLogin) {
  //     next('/')
  //     return
  //   }
  // }
  // next() // 必须使用 next ,执行效果依赖 next 方法的调用参数
})


export default router
